/**
 * @param {string} s
 * @return {string}
 */
var smallestSubsequence = function (s) {
  let stack = []
  let map = {}
  let inStack = {}
  for (let char of s) {
    if (map[char] === undefined) {
      map[char] = 0
    }
    map[char]++
  }
  for (let char of s) {
    map[char]--
    if (inStack[char]) continue
    while (stack.length !== 0 && stack[stack.length - 1] > char) {
      if (map[stack[stack.length - 1]] === 0) {
        break
      }
      let charPop = stack.pop()
      inStack[charPop] = false
    }
    stack.push(char)
    inStack[char] = true
  }
  return stack.join('')
}
